package com.ruoyi.framework.weChat.api;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.exception.CustomException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @Classname SocialProperties
 * @Description 微信-用户信息获取
 * @Author h21448-hxtq
 * @Date 2020-04-01 13 : 57
 * @Version 1.0
 */
public class WeChatImpl extends AbstractOAuth2ApiBinding implements WeChat {
    /**
     * 微信-获取用户信息的url
     */
    private static final String WECHAT_GET_USER_INFO_URL="https://api.weixin.qq.com/sns/userinfo?openid=";

    private ObjectMapper objectMapper=new ObjectMapper();

    public WeChatImpl(String accessToken) {
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
    }
    //微信-获取用户信息
    public WeChatUserInfo getUserInfo(String openId){
        String url=WECHAT_GET_USER_INFO_URL+openId;
        String result=getRestTemplate().getForObject(url,String.class);
        //如包含错误码，返回null
        if (StringUtils.contains(result,"errcode")) {
            return null;
        }

        WeChatUserInfo userInfo=null;

        try {
            userInfo = objectMapper.readValue(result,WeChatUserInfo.class);
        } catch (Exception e) {
            throw new CustomException(e.getMessage() +",获取微信用户信息失败");
        }

        return userInfo;
    }

    /**
     * 使用utf-8 替换默认的ISO-8859-1编码
     * @return
     */
    @Override
    protected List<HttpMessageConverter<?>> getMessageConverters() {
        List<HttpMessageConverter<?>> messageConverters = super.getMessageConverters();
        messageConverters.remove(0);
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return messageConverters;
    }

}
